from django.core.paginator import Paginator
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse
from django.utils import timezone

from .models import UserPoints, PointsRecord, Reward, RewardExchange
from .utils import deduct_points


@login_required
def points_home(request):
    """积分首页"""
    user_points, created = UserPoints.objects.get_or_create(user=request.user)
    recent_records = PointsRecord.objects.filter(user=request.user).order_by('-created_at')[:10]
    
    context = {
        'user_points': user_points,
        'recent_records': recent_records,
    }
    return render(request, 'points/points_home.html', context)


@login_required
def points_records(request):
    """积分记录"""
    records_list = PointsRecord.objects.filter(user=request.user).order_by('-created_at')

    # 添加分页
    paginator = Paginator(records_list, 20)  # 每页20条
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    context = {
        'records': page_obj,
    }
    return render(request, 'points/points_records.html', context)

@login_required
def rewards_shop(request):
    """积分商城"""
    rewards = Reward.objects.filter(is_active=True, stock__gt=0).order_by('points_required')
    user_points, created = UserPoints.objects.get_or_create(user=request.user)
    
    context = {
        'rewards': rewards,
        'user_points': user_points,
    }
    return render(request, 'points/rewards_shop.html', context)


@login_required
def reward_detail(request, reward_id):
    """奖品详情"""
    reward = get_object_or_404(Reward, id=reward_id)
    user_points, created = UserPoints.objects.get_or_create(user=request.user)
    
    context = {
        'reward': reward,
        'user_points': user_points,
    }
    return render(request, 'points/reward_detail.html', context)


@login_required
def reward_exchange(request, reward_id):
    """兑换奖品"""
    if request.method == 'POST':
        reward = get_object_or_404(Reward, id=reward_id)
        
        # 检查奖品是否可用
        if not reward.is_active:
            return JsonResponse({'success': False, 'message': '该奖品已下架'})
        
        if reward.stock <= 0:
            return JsonResponse({'success': False, 'message': '该奖品已兑完'})
        
        # 检查积分是否足够
        user_points, created = UserPoints.objects.get_or_create(user=request.user)
        if user_points.available_points < reward.points_required:
            return JsonResponse({'success': False, 'message': '积分不足'})
        
        # 扣除积分
        if deduct_points(request.user, reward.points_required, f'兑换奖品：{reward.name}'):
            # 创建兑换记录
            RewardExchange.objects.create(
                user=request.user,
                reward=reward,
                points_used=reward.points_required,
                status='pending'
            )
            
            # 减少库存
            reward.stock -= 1
            reward.save()
            
            messages.success(request, '兑换成功，请等待处理')
            return JsonResponse({'success': True, 'message': '兑换成功'})
        else:
            return JsonResponse({'success': False, 'message': '积分扣除失败'})
    
    return JsonResponse({'success': False, 'message': '请求方法错误'})


@login_required
def exchange_history(request):
    """兑换记录"""
    exchanges = RewardExchange.objects.filter(user=request.user).select_related('reward').order_by('-created_at')
    context = {'exchanges': exchanges}
    return render(request, 'points/exchange_history.html', context)
